import router from './router'
import store from './store'
import { getUserData } from '@/utils/loginauth.js'
import { Message } from 'element-ui'

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach((to, from, next) => {
	// let local = window.location.href
	var partnershipCode = 0
	if (JSON.parse(window.sessionStorage.getItem('currentUser'))) {
		partnershipCode = JSON.parse(window.sessionStorage.getItem('currentUser')).partnershipCode
	} else {
		partnershipCode = 0
	}
	// 微信授权登录
	if (to.path == '/alarm-data' || to.path == '/realtime-data') {
		next()
	} else if (to.path === '/weekly-electricity-report') {
		next()
	} else {
		const hasUser = getUserData()
		if (hasUser) {
			if (to.path == '/login'

			) {
				next({ path: '/' })
			} else {
				const hasPermissions = store.getters.rolePermissions && store.getters.rolePermissions.length > 0
			
				if (hasPermissions) {
					next()
			
				} else {
					try {
						store
							.dispatch('user/getRolePermission')
							.then((rolePermissions) => {
								store.dispatch('permission/generateRoutes', rolePermissions).then((accessRoutes) => {
							
									if (accessRoutes.length > 0) {
										router.addRoutes(accessRoutes)

										next({ ...to, replace: true })
									} else {
										next()
									}
								})
							})
							.catch(() => {
								//Message.error('该账号未设置任何角色')
								next(`/login?redirect=${to.path}`)
								// store.dispatch('user/logoutAction')
							})
					} catch (error) {
						// remove token and go to login page to re-login
						store.dispatch('user/resetUser')
						next(`/login?redirect=${to.path}`)
					}
				}
			}
		} else {
			let url = location.search
			if (whiteList.indexOf(to.path) !== -1) {
				next()
			} else if (url.indexOf('code') != -1) {
				let str = url.substr(1)
				let strs = str.split('&')
				let code = strs[0].split('=')[1]
				console.log(code)
				store
					.dispatch('user/getOpenId', code)
					.then((res) => {
						const resp = res.data
						if (resp.errcode == 1) {
							if (store.getters.partnershipCode != undefined) {
								next(`/login?code=${store.getters.partnershipCode}`)
							} else {
								next(`/login`)
							}
						} else {
							window.location.href = location.origin + location.pathname + location.hash
							next()
						}
					})
					.catch(() => { })
			} else {
				if (store.getters.partnershipCode != undefined) {
					next(`/login?code=${store.getters.partnershipCode}`)
				} else {
					next(`/login`)
				}

			}
		}
	}
})
